package term

import (
	"context"
	"strings"

	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateTermLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateTermLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateTermLogic {
	return &CreateTermLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateTermLogic) CreateTerm(req *types.CreateMediaTermReq) (resp *types.BaseMsgResp, err error) {
	if req.Name == nil || len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "term.nameRequired"))
	}

	var meta []*attachmentclient.MetaInfo
	if req.Meta != nil && len(req.Meta) > 0 {
		for _, m := range req.Meta {
			meta = append(meta, &attachmentclient.MetaInfo{
				Key:   m.Key,
				Value: m.Value,
			})
		}
	}
	res, err := l.svcCtx.AttachmentRpc.BackendCreateTerm(l.ctx, &attachmentclient.TermInfo{
		Name:     req.Name,
		Slug:     req.Slug,
		Taxonomy: req.Taxonomy,
		ParentId: req.ParentId,
		GroupId:  req.GroupId,
		Desc:     req.Desc,
		Sort:     req.Sort,
		Status:   req.Status,
		Meta:     meta,
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
